package com.example.demo.controller;

import com.example.demo.dto.CommonResult;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping({"/upload"})
public class UploadController {
    @Value("${img.prefix}")
    private String imgPrefix;



    @RequestMapping({"/test"})
    @ResponseBody
    public String index() {
        return "upload";
    }

    @RequestMapping(value = {"/img"}, method = {RequestMethod.POST})
    @ResponseBody
    public CommonResult fileUpload(MultipartFile srcFile) {
        if (srcFile.isEmpty())
            return CommonResult.failed("");
                    String newFileName = "";
        String times = "";
        try {
            File destFile = new File("C:\\Users");
            if (!destFile.exists())
                destFile = new File("");
            System.out.println("file path:" + destFile.getAbsolutePath());
            SimpleDateFormat sf_ = new SimpleDateFormat("yyyyMMdd");
            times = sf_.format(new Date());
            File upload = new File(destFile.getAbsolutePath(), "picture/" + times);
            if (!upload.exists())
                upload.mkdirs();

            byte[] bytes = srcFile.getBytes();
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            String fileName = srcFile.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            newFileName = uuid + "." + suffixName;
            Path path = Paths.get(upload.getAbsolutePath() + "/" + newFileName, new String[0]);
            Files.write(path, bytes, new java.nio.file.OpenOption[0]);
            System.out.println(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
        new CommonResult();
        return CommonResult.success(imgPrefix + times + "/" + newFileName);
    }
}
